import random
from time import sleep

import cv2
import pyautogui
import pygetwindow as gw
import time
import numpy as np
from pyautogui import click


def find_window():
    target_window_title = "跳一跳"
    target_window = gw.getWindowsWithTitle(target_window_title)
    if target_window:
        # print(f"找到窗口：{target_window_title}")
        window = target_window[0]
        return window
    else:
        print("未找到该窗口！")

def take_screenshot(window):
    left = window.left + 13
    top = window.top + 5
    width = window.width - 25
    height = window.height - 15

    screenshot = pyautogui.screenshot(region=(left, top, width, height))
    # print(left,top,width,height)
    screenshot.save("1.png")
    # print("截图已保存为 1.png")
    return left,top

def click_mouse(distance,screen_left,screen_top,tm):
    # print("distance :" , distance)
    randX = random.randint(1,8)*50
    randY = random.randint(12,14)*50
    mouse_left = screen_left + randX
    mouse_top = screen_top + 50 + randY
    #不在一个坐标重复点击，随机点击某一个坐标
    pyautogui.moveTo(mouse_left, mouse_top)

    # if tm == 0:
    #     click_time = 0.6061046851578659
    #     tm += 1
    # else:
    if distance < 178:
        click_time = 0.45 * distance/161.07451691686057
    else:
        click_time = 0.70 * distance / 225.21101216414795
    # print("ClickTime :", tm)
    # 按下鼠标左键
    print(click_time)
    pyautogui.mouseDown()
    time.sleep(tm)
    time.sleep(click_time)
    # 释放鼠标左键
    pyautogui.mouseUp()

# # 裁剪图片
# def crop_image(img):
#     # 获取图像的高度和宽度
#     height, width = img.shape[:2]
#     # 裁剪图像，从上下左右各裁剪5个像素点
#     cropped_img = img[10:height-10, 10:width-10]
#     return cropped_img
#     # # 显示裁剪后的图像
#     # cv2.imshow('Cropped Image', cropped_img)

#定位跳棋
def get_player(img,player_template):
    player = cv2.matchTemplate(img, player_template, cv2.TM_CCOEFF_NORMED)
    # 获取匹配结果中的最小值、最大值、最小值坐标和最大值坐标
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(player)

    corner_loc = (max_loc[0] + 37, max_loc[1] + 88)
    player_spot = (max_loc[0] + 18, max_loc[1] + 88)
    cv2.circle(img, player_spot, 10, (0, 255, 255), -1)
    cv2.rectangle(img, max_loc, corner_loc, (0,0,255), 5)

    return img,player_spot

#定位跳台
def get_center(image, test ):
    # image = cv2.imread('images/5.png')
    blurred_img = cv2.GaussianBlur(image, (5, 5), 0)  # 高斯模糊
    canny_img = cv2.Canny(blurred_img, 1, 10)  # 边缘检测

    height, width = canny_img.shape
    crop_img = canny_img[300:int(height / 2), 0:width]
    # #消除小跳棋
    # for y in range(max_loc[1], max_loc[1]+150):
    #     for x in range(max_loc[0], max_loc[0] + 50):
    #         canny_img[y][x] = 0

    # 获取中心点坐标
    crop_h, crop_w = crop_img.shape
    center_x, center_y = 0, 0
    max_x = 0
    for y in range(crop_h):
        for x in range(crop_w):
            if crop_img[y, x] == 255:
                if center_x == 0:
                    center_x = x
                if x > max_x:
                    center_y = y
                    max_x = x

    if test == 1 :
        center_y = center_y - 17
    # cv2.circle(crop_img, (center_x, center_y), 10, 255, -1)
    # cv2.imshow('crop_img', crop_img)
    center_y = center_y + 300
    cv2.circle(image, (center_x, center_y), 10, 255, -1)
    # cv2.imshow('Img', image)
    return image,center_x,center_y

def main():
    tm = 0
    while True:
        test = 0
        window = find_window()
        if window:
            left,top = take_screenshot(window)
        img = cv2.imread("1.png")  # 读取原始图像
        x, y =img.shape[:2]
        player_template = cv2.imread("people.png")  # 读取跳棋模板图像
        gameover_template = cv2.imread("gameover.png")  # 读取游戏结束模板图像

        res_end = cv2.matchTemplate(img, gameover_template, cv2.TM_CCOEFF_NORMED)
        _, max_val, _, _ = cv2.minMaxLoc(res_end)
        if max_val > 0.6:
            print("Game Over!")
            break
        img,player_spot = get_player(img, player_template)

        if player_spot[0] > 240:
            player_spot = y - player_spot[0],player_spot[1]
            img = cv2.flip(img, 1)
            test = 1

        img,center_x,center_y= get_center(img, test)
        # cv2.imshow('Img', img)
        print(player_spot[0],player_spot[1])
        print(center_x,center_y)
        distance = (player_spot[0] - center_x) ** 2 + (player_spot[1] - center_y) ** 2
        distance = distance ** 0.5
        print("distance:", distance )
        # tm = float(input())
        click_mouse(distance,left,top,tm)
        # time.sleep(0.5)
        cv2.waitKey(0)
        cv2.destroyAllWindows()


if __name__ == '__main__':
    main()